<?php

namespace app\api\model;

use app\api\model\CustomerCategory;
use think\Model;
use think\Db;
use app\api\model\Goods\Speci\Brand;
use app\api\model\Goods\Speci\Category;
use think\exception\DbException;
use app\api\model\Goods\Speci\Color;
use app\api\model\Goods\Speci\Size;

class MarkeModel extends Base {

    private $color_m;
    private $size_m;
    private $brand_m;
    private $category_m;

    public function __construct() {
        parent::__construct();
        $this->color_m = new Color;
        $this->brand_m = new Brand;
        $this->size_m = new Size;
        $this->category_m = new Category;
    }

    //积分规则列表
    public function getIntegral() {
        $list = $this->getPage('integral_rule', '*', [], 'id desc', '', '');
        $list = $list->toArray();
        foreach ($list['data'] as $k => $v) {
            $list['data'][$k]['cid_name'] = $this->getValue('customer_category', ['id' => $v['cid']], 'name');
            $list['data'][$k]['product_num'] = count(explode(',', $v['goods']));
        }
        return $list;
    }

    //新增积分规则
    public function getIntegralAdd($data) {
        $list = $this->getAdd('integral_rule', $data);
        //更新商品积分规则
        $goods_arr = explode(',', $data['goods']);
        db('shop')->whereIn('id', $goods_arr)->update(['rule' => $list]);
        return $list;
    }

    //编辑积分规则
    public function getIntegralEdit($id, $data) {
        //更新商品积分规则
        $info = db('integral_rule')->where(['id' => $id])->field('goods')->find();
        db('shop')->whereIn('id', explode(',', $info['goods']))->update(['rule' => 0]);
        db('shop')->whereIn('id', explode(',', $data['goods']))->update(['rule' => $id]);
        $list = $this->getEdit('integral_rule', ['id' => $id], $data);
        return $list;
    }

    public function getIntegralShop($data) {
        $where = [];
        if ($data['name']) {
            $where[] = ['name', 'like', '%' . $data['name'] . '%'];
        }
        if (!empty($data['category'])) {
            $where[] = ['category', '=', $data['category']];
        }
        if (isset($data['status'])) {
            $where[] = ['status', '=', $data['status']];
        }
        if (!empty($data['brand'])) {
            $where[] = ['brand', '=', $data['brand']];
        }
        if (!empty($data['rule'])) {
            $where[] = ['rule', '=', $data['rule']];
        }

        $list = $this->getPage('shop', 'id,product_id,name,category,brand,rule,status,item,goods_code,commodity_id', $where, 'id desc', $data['page'], $data['size']);
        $list = $list->toArray();
        foreach ($list['data'] as $k => $v) {
            $list['data'][$k]['category'] = $this->getValue('category', ['id' => $v['category']], 'name');
            $list['data'][$k]['brand'] = $this->getValue('color1', ['id' => $v['brand']], 'name');
            $list['data'][$k]['rule'] = $this->getValue('integral_rule', ['id' => $v['rule']], 'name');
            $list['data'][$k]['images'] = json_decode($this->getValue('commodity', ['id' => $v['commodity_id']], 'images'), true);
            switch ($v['status']) {
                case 0:
                    $list['data'][$k]['status'] = '已上架';
                    break;
                default:
                    $list['data'][$k]['status'] = '已下架';
            }
        }
        return $list;
    }

    //积分规则详情
    public function getIntegralInfo($id) {
        $list = $this->getOne('integral_rule', '*', ['id' => $id]);
        //单品信息
        $goods_id = explode(',', $list['goods']);
//        $list['goods'] = db('product')->alias('p')->leftJoin('commodity', 'p.commodity_id = commodity.id')->field('p.id,commodity.name')->whereIn('p.id', $goods_id)->select();
        $list['goods'] = db('shop')->whereIn('id', $goods_id)->field('id,name')->select();
        $list['cid_name'] = $this->getValue('customer_category', ['id' => $list['cid']], 'name');
        return $list;
    }

    public function getIntegralDel($id) {
        $list = $this->getOne('integral_rule', '*', ['id' => $id]);
        $custom = $this->getOne('user', '*', ['category' => $list['cid'], 'status' => 0]);
        if (!empty($custom)) {
            return 1;
        } else {
            $this->getDel('integral_rule', ['id' => $id]);
            return 2;
        }
    }

    public function getMemberCard($id, $data) {
        $list = $this->getEdit('member_card', ['id' => $id], $data);
        return $list;
    }

    public function getDiscount($data) {
        $where = [];
        if (!empty($data['status'])) {
            $where[] = ['status', '=', $data['status']];
        }
        $list = $this->getPage('discount', '*', $where, 'id desc', $data['page'], $data['size']);
        $list = $list->toArray();
        foreach ($list['data'] as $k => $v) {
            $list['data'][$k]['start_time'] = date('Y-m-d H:i:s', $v['start_time']);
            $list['data'][$k]['end_time'] = date('Y-m-d H:i:s', $v['end_time']);
            $list['data'][$k]['maker'] = $this->getValue('admin', ['id' => $v['maker']], 'name');
        }
        return $list;
    }

    public function getDiscountAdd($data) {
        $data['ctime'] = time();
        $goods = $data['goods'];
        unset($data['goods']);
        $list = $this->getAdd('discount', $data);
        foreach ($goods as $k => $v) {
            $rel['goods_id'] = $v['id'];
            $rel['original'] = $v['original'];
            $rel['discount'] = isset($v['discount']) ? $v['discount'] : 100;
            $rel['discount_price'] = $v['discount_price'];
            $rel['pid'] = $list;
            $this->getAdd('discount_relation', $rel);
        }
        return $list;
    }

    public function getDiscountEdit($id, $data) {
        $arr = $this->getOne('discount', '*', ['id' => $id]);
        if ($arr['status'] == 1) {
            $goods = $data['goods'];
            unset($data['goods']);
            $this->getEdit('discount', ['id' => $id], $data);
            //编辑关联表
            db('discount_relation')->where(['pid' => $id])->delete();
            foreach ($goods as $k => $v) {
                $rel['goods_id'] = $v['id'];
                $rel['original'] = $v['original'];
                $rel['discount'] = isset($v['discount']) ? $v['discount'] : 100;
                $rel['discount_price'] = $v['discount_price'];
                $rel['pid'] = $id;
                $this->getAdd('discount_relation', $rel);
            }
            return 1;
        } else {
            return 2;
        }
    }

    /**
     * 获取分销列表
     * @param type $page
     * @param type $size
     * @param type $where
     */
    public function getRetailLogsList($page, $size, $where) {
        $limit = ($page - 1) * $size;
        $sql = 'select l.*,o.id as order_id,u.phone,u.name,u.category,u.nickname from jxc_retail_logs as l '
                . 'left join jxc_order as o on l.order_num = o.order_num '
                . 'left join jxc_user as u on o.user_id = u.id '
                . 'where ' . $where . ' limit ' . $limit . ',' . $size;
        $list = Db::query($sql);
        if (!empty($list)) {
            //处理输出数据
            foreach ($list as &$val) {
                //分销状态
                switch ($val['status']) {
                    case 1:
                        $val['status_name'] = '未完成';
                        break;
                    case 2:
                        $val['status_name'] = '已取消';
                        break;
                    case 3:
                        $val['status_name'] = '佣金未转账';
                        break;
                    case 4:
                        $val['status_name'] = '佣金已转账';
                        break;
                    default:
                        break;
                }
                //客户类别
                $cate_name = db('customer_category')->where(['id' => $val['category']])->column('name');
                $val['cate_name'] = !empty($cate_name) ? current($cate_name) : '';
                //商品数量
                $shop_num = db('order_relation')->where(['pid' => $val['order_id']])->column('num');
                $val['shop_num'] = !empty($shop_num) ? current($shop_num) : 0;
                //分销客户名称
                $share_user = db('user')->whereIn('id', [$val['retail_user1'], $val['retail_user2']])->field('name')->select();
                $val['retail_user1_name'] = !empty($share_user) ? $share_user[0]['name'] : '';
                $val['retail_user2_name'] = !empty($share_user) ? $share_user[1]['name'] : '';
                //时间
                $val['ctime_date'] = !empty($val['ctime']) ? date('Y-m-d H:i:s', $val['ctime']) : '';
                $val['retail_time1_date'] = !empty($val['retail_time1']) ? date('Y-m-d H:i:s', $val['retail_time1']) : '';
                $val['retail_time2_date'] = !empty($val['retail_time2']) ? date('Y-m-d H:i:s', $val['retail_time2']) : '';
            }
            unset($val);
        }
        $sql_c = 'select l.*,o.phone,u.name,u.category,u.nickname from jxc_retail_logs as l '
                . 'left join jxc_order as o on l.order_num = o.order_num '
                . 'left join jxc_user as u on o.phone = u.phone '
                . 'where ' . $where;
        $list_c = Db::query($sql_c);
        //总条数
        $total = count($list_c);
        //总页码
        $last_page = intval(ceil($total / $size));
        return array(
            'current_page' => $page, //当前页
            'per_page' => $size, //每页条数
            'last_page' => $last_page, //总页数
            'total' => $total, //总条数
            'data' => $list, //数据数组
        );
    }

    /**
     * 获取分销统计数据
     */
    public function getRetailTotal() {
        $data = db('retail_logs')->field('count(if(status=1,1,null)) as undone_num,count(if(status=2,1,null)) as cancel_num,'
                        . 'count(if(status < 4,1,null)) as untransfer_num,count(if(status=4,1,null)) as transfered_num,sum(order_money) as total_order_money,'
                        . 'sum(total_retail) as total_retail,sum(if(status < 4,total_retail,0)) as undo_total_retail')->select();
        return current($data);
    }

    public function getDiscountInfo($id) {
        $arr = $this->getOne('discount', '*', ['id' => $id]);
        $arr['start_time'] = date('Y-m-d H:i:s', $arr['start_time']);
        $arr['end_time'] = date('Y-m-d H:i:s', $arr['end_time']);
        $maker = db('admin')->where(['id' => $arr['maker']])->field('name')->find();
        $arr['maker'] = !empty($maker) ? $maker['name'] : '';
        $arr['goods'] = $this->getselectList('discount_relation', '*', ['pid' => $id]);
        foreach ($arr['goods'] as $k => $v) {
            $shop_name = db('shop')->where(['id' => $v['goods_id']])->field('name')->find();
            $arr['goods'][$k]['name'] = !empty($shop_name) ? $shop_name['name'] : '';
        }
        return $arr;
    }

    public function getDiscountshop($data) {
        $where = [];
        if ($data['name']) {
            $where[] = ['name', 'like', '%' . $data['name'] . '%'];
        }
        if (!empty($data['category'])) {
            $where[] = ['category', '=', $data['category']];
        }
        if (!empty($data['status'])) {
            $where[] = ['status', '=', $data['status']];
        }
        if (!empty($data['brand'])) {
            $where[] = ['brand', '=', $data['brand']];
        }
        $list = $this->getPage('shop', 'id,name,price,item,status,goods_code,brand,category,tag,type', $where, 'id desc', $data['page'], $data['size']);
        $list = $list->toArray();
        foreach ($list['data'] as $k => $v) {
            switch ($v['status']) {
                case 0:
                    $list['data'][$k]['status'] = '已上架';
                    break;
                default:
                    $list['data'][$k]['status'] = '已下架';
            }
            //品牌等信息
            $list['data'][$k]['brand_name'] = $this->brand_m->find($v['brand'])['name'];
            $list['data'][$k]['category_name'] = $this->brand_m->find($v['category'])['name'];
        }
        return $list;
    }

    public function getDiscountDel($id) {
        $arr = $this->getOne('discount', '*', ['id' => $id]);
        if ($arr['status'] == 1) {
            $this->getDel('discount', $id);
            return 1;
        } else {
            return 2;
        }
    }

    public function getDiscountRevoke($id) {
        $arr = $this->getOne('discount', '*', ['id' => $id]);
        if ($arr['status'] == 1) {
            $this->getSetField('discount', ['id' => $id], ['status' => 4]);
            return 1;
        } else {
            return 2;
        }
    }

    //优惠券列表
    public function getCouponList($page, $size, $status) {
        $list = db('coupon')->where(['status' => $status])->field('id,type,name,create_time,fail_time')->limit($page, $size)->paginate($size)->toArray();
        foreach ($list['data'] as $k => $v) {
            $list['data'][$k]['type_name'] = $v['type'] == 1 ? '新用户' : '普通';
            $list['data'][$k]['create_time'] = date('Y-m-d H:i:s', $v['create_time']);
            $list['data'][$k]['fail_time'] = date('Y-m-d H:i:s', $v['fail_time']);
            //使用人数统计(未完成)
            $used_num = db('coupon_member')->where(['status' => 1,'coupon_id' => $v['id']])->count();            
            $list['data'][$k]['used_num'] = $used_num;
            //领取人数
            $get_num = db('coupon_member')->where(['coupon_id' => $v['id']])->count();
            $list['data'][$k]['get_num'] = $get_num;
        }
        return $list;
    }

    public function getCouponAdd($data) {
        $list = $this->getAdd('coupon', $data);
        return $list;
    }

    public function getCouponEdit($id, $data) {
        $arr = $this->getOne('coupon', '*', ['id' => $id]);
        if ($arr['status'] == 1) {
            $data['goods'] = json_encode($data['goods']);
            $this->getEdit('coupon', ['id' => $id], $data);
            return 1;
        } else {
            return 2;
        }
    }

    public function getCouponInfo($id) {
        $arr = $this->getOne('coupon', '*', ['id' => $id]);
        $arr['goods'] = json_decode($arr['goods'], TRUE);
        $arr['create_time'] = date('Y-m-d H:i:s', $arr['create_time']);
        $arr['fail_time'] = date('Y-m-d H:i:s', $arr['fail_time']);
        return $arr;
    }

    public function getCouponDel($id) {
        $arr = $this->getOne('coupon', '*', ['id' => $id]);
        if ($arr['status'] == 1) {
            $this->getDel('coupon', $id);
            return 1;
        } else {
            return 2;
        }
    }

    public function getSeckill($data) {
        $where = [];
        if (!empty($data['status'])) {
            $where['status'] = $data['status'];
        }
        $list = $this->getPage('seckill', 'id,name,start_time,end_time,num,maker', $where, 'id desc', $data['page'], $data['size']);
        $list = $list->toArray();
        foreach ($list['data'] as $k => $v) {
            $list['data'][$k]['start_time'] = date('Y-m-d H:i:s', $v['start_time']);
            $list['data'][$k]['end_time'] = date('Y-m-d H:i:s', $v['end_time']);
            $list['data'][$k]['maker'] = $this->getValue('admin', ['id' => $v['maker']], 'name');
            //单品信息
            $good_lsit = db('seckill_relation')->where(['pid' => $v['id']])->field('goods_id,original,seckill,num')->select();
            if (!empty($good_lsit)) {
                foreach ($good_lsit as $kk => $vv) {
                    $shop_info = db('product')->where(['id' => $vv['goods_id']])->field('commodity_id,color,size')->find();
                    $shop_name = db('commodity')->where(['id' => $shop_info['commodity_id']])->column('name');
                    $good_lsit[$kk]['name'] = !empty($shop_name) ? current($shop_name) : '';
                    //颜色，尺码
                    $good_lsit[$kk]['color'] = $shop_info['color'];
                    $good_lsit[$kk]['size'] = $shop_info['size'];
                    $good_lsit[$kk]['color_name'] = $this->color_m->find($shop_info['color'])['name'];
                    $good_lsit[$kk]['size_name'] = $this->size_m->find($shop_info['size'])['name'];
                }
            }
            $list['data'][$k]['goods'] = $good_lsit;
        }
        return $list;
    }

    public function getSeckillAdd($data) {
        $arr = $this->getAdd('seckill', $data);
        foreach ($data['goods'] as $k => $v) {
            $rel['goods_id'] = $v['id'];
            $rel['original'] = $v['original'];
            $rel['seckill'] = isset($v['seckill_price']) ? $v['seckill_price'] : $rel['original'];
            $rel['num'] = isset($v['seckill_num']) ? $v['seckill_num'] : 1;
            $rel['pid'] = $arr;
            $this->getAdd('seckill_relation', $rel);
        }
        return $arr;
    }

    public function getSeckillOnline($id) {
//        $arr = $this->getOne('seckill', '*', ['id' => $id]);
//        if($arr['start_time'] >= time()){
        return $this->getSetField('seckill', ['id' => $id], ['status' => 2]);
//        }else{
//            throw new \Exception('活动超过开始时间');
//        }
    }

    public function getSeckillEdit($id, $data) {
        $arr = $this->getOne('seckill', '*', ['id' => $id]);
        if ($arr['status'] == 1) {
            $goods = $data['goods'];
            unset($data['goods']);
            $this->getEdit('seckill', ['id' => $id], $data);
            //先将之前的关联清除
            db('seckill_relation')->where(['pid' => $id])->delete();
            foreach ($goods as $k => $v) {
                $rel['goods_id'] = $v['id'];
                $rel['original'] = $v['original'];
                $rel['seckill'] = isset($v['seckill_price']) ? $v['seckill_price'] : $rel['original'];
                $rel['num'] = isset($v['seckill_num']) ? $v['seckill_num'] : 1;
                $rel['pid'] = $id;
                $this->getAdd('seckill_relation', $rel);
            }
            return 1;
        } else {
            return 2;
        }
    }

    public function getSeckillInfo($id) {
        $arr = $this->getOne('seckill', '*', ['id' => $id]);
        $arr['start_time'] = date('Y-m-d H:i:s', $arr['start_time']);
        $arr['end_time'] = date('Y-m-d H:i:s', $arr['end_time']);
        $arr['maker'] = $this->getValue('admin', ['id' => $arr['maker']], 'name');
        //单品信息
        $good_lsit = db('seckill_relation')->where(['pid' => $id])->field('goods_id as id,original,seckill as seckill_price,num as seckill_num')->select();
        if (!empty($good_lsit)) {
            foreach ($good_lsit as $kk => $vv) {
                $shop_info = db('product')->where(['id' => $vv['id']])->field('id,commodity_id,color,size')->find();
                $shop_name = db('commodity')->where(['id' => $shop_info['commodity_id']])->column('name');
                $good_lsit[$kk]['name'] = !empty($shop_name) ? current($shop_name) : '';
                //库存数量
                $good_lsit[$kk]['stock'] = db('product_stock')->where(['product_id' => $shop_info['id']])->sum('stock');
                //颜色，尺码
                $good_lsit[$kk]['color'] = $shop_info['color'];
                $good_lsit[$kk]['size'] = $shop_info['size'];
                $good_lsit[$kk]['color_name'] = $this->color_m->find($shop_info['color'])['name'];
                $good_lsit[$kk]['size_name'] = $this->size_m->find($shop_info['size'])['name'];
            }
        }
        $arr['goods'] = $good_lsit;
        return $arr;
    }

    public function getSeckillStop($id) {
        $arr = $this->getOne('seckill', '*', ['id' => $id]);
        if (in_array($arr['status'], [1, 2])) {
            $this->getSetField('seckill', ['id' => $id], ['status' => 5]);
            return 1;
        } else {
            return 2;
        }
    }

    public function getSeckillDel($id) {
        $arr = $this->getOne('seckill', '*', ['id' => $id]);
        if (in_array($arr['status'], [1])) {
            $this->getDel('seckill', $id);
            //清除关联信息
            db('seckill_relation')->where(['pid' => $id])->delete();
            return 1;
        } else {
            return 2;
        }
    }

    //编辑分销规则
    public function getRetailEdit($data) {
        $info = db('retail_rules')->order('id', 'desc')->find();
        if (!empty($info)) {
            $res = db('retail_rules')->where(['id' => $info['id']])->update($data);
        } else {
            $res = db('retail_rules')->insert($data);
        }
        return $res;
    }

    //获取分销规则信息
    public function getRetailInfo() {
        $info = db('retail_rules')->order('id', 'desc')->find();
        if (!empty($info)) {
            if (!empty($info['goods'])) {
                $goods = explode(',', $info['goods']);
                $info['goods'] = db('shop')->whereIn('id', $goods)->field('id,name')->select();
            } else {
                $info['goods'] = [];
            }
            $info['custom'] = explode(',', $info['custom']);
            if (!empty($info['zizhi'])) {
                $zizhi = explode(',', $info['zizhi']);
                $info['zizhi'] = db('user')->whereIn('id', $zizhi)->field('id,name')->select();
            } else {
                $info['zizhi'] = [];
            }
        }
        return $info;
    }

    public function getretailGoods($data) {
        $where = [];
        if (!empty($data['name'])) {
            $where[] = ['name', 'like', '%' . $data['name'] . '%'];
        }
        if (!empty($data['status'])) {
            $where[] = ['status', '=', $data['status']];
        }
        if (!empty($data['category'])) {
            $where[] = ['category', '=', $data['category']];
        }
        if (!empty($data['brand'])) {
            $where[] = ['brand', '=', $data['brand']];
        }
        $list = $this->getPage('shop', 'id,category,name,brand,item,goods_code,status', $where, 'id desc', $data['page'], $data['size']);
        $list = $list->toArray();
        foreach ($list['data'] as $k => $v) {
            $list['data'][$k]['category'] = $this->getValue('category', ['id' => $v['category']], 'name');
            $list['data'][$k]['brand'] = $this->getValue('color1', ['id' => $v['brand']], 'name');
            switch ($v['status']) {
                case 0:
                    $list['data'][$k]['status1'] = '已上架';
                    break;
                default:
                    $list['data'][$k]['status1'] = '已下架';
            }
        }
        return $list;
    }

    public function getretailCustomer($data) {
        $where = [];
        if (!empty($data['name'])) {
            $where[] = ['name', 'like', '%' . $data['name'] . '%'];
        }
        if (!empty($data['category'])) {
            $where[] = ['category', '=', $data['category']];
        }
        $list = $this->getPage('user', 'id,category,name,phone,we_nickname', $where, 'id desc', $data['page'], $data['size']);
        $list = $list->toArray();
        foreach ($list['data'] as $k => $v) {
            $list['data'][$k]['category'] = $this->getValue('customer_category', ['id' => $v['category']], 'name');
        }
        return $list;
    }

    /**
     * 获取商品列表
     * @param type $page
     * @param type $size
     * @param type $where
     */
    public function getCommodityList($page, $size, $where) {
        $list = db('commodity')->where($where)->field('id,name,item,retail_price,category,brand,status')->limit($page, $size)->paginate($size)->toArray();
        //计算库存
        if (!empty($list['data'])) {
            $brand_m = new Brand;
            $cate_m = new Category;
            foreach ($list['data'] as &$val) {
                $val['com_stock'] = db('product_stock')->where(['commodity_id' => $val['id']])->sum('stock');
                $brand_info = $brand_m->info($val['brand']);
                $val['brand_name'] = !empty($brand_info) ? $brand_info['name'] : '';
                $cate_info = $cate_m->info($val['category']);
                $val['category_name'] = !empty($cate_info) ? $cate_info['name'] : '';
                $val['status_name'] = $val['status'] ? '启用' : '禁用';
            }
            unset($val);
        }
        return $list;
    }

    /**
     * 获取商品下所有单品列表
     * @param type $com_id
     * @param type $page
     * @param type $size
     * @param type $where
     */
    public function getProductList($com_id, $page, $size, $where = '1=1') {
        $list = db('product')->where(['commodity_id' => $com_id])->where($where)->limit($page, $size)->paginate($size)->toArray();
        if (!empty($list['data'])) {
            $com = db('commodity')->where(['id' => $com_id])->field('name,retail_price')->find();
            foreach ($list['data'] as &$val) {
                $val['name'] = !empty($com) ? $com['name'] : '';
                $val['original'] = !empty($com) ? $com['retail_price'] : '';
                //库存数量
                $val['stock'] = db('product_stock')->where(['product_id' => $val['id']])->sum('stock');
                //颜色，尺码
                $val['color_name'] = $this->color_m->find($val['color'])['name'];
                $val['size_name'] = $this->size_m->find($val['size'])['name'];
                //秒杀价，秒杀数量
                $val['seckill_price'] = 0.00;
                $val['seckill_num'] = 0;
            }
            unset($val);
        }
        return $list;
    }

}
